package com.ejlchina.tool.fragment.viewpager

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.adolf.androiddemo.databinding.FragmentFullAndDistancePagerBinding
import com.ejlchina.tool.base.BaseBindingFragment
import com.ejlchina.tool.bean.BleDeviceBean
import com.ejlchina.tool.enums.OnOffEnum
import com.ejlchina.tool.enums.SuccessFailEnum
import com.ejlchina.tool.util.COMMAND_EXTEND_SERIAL_PORT_GET_DOWNWARD
import com.ejlchina.tool.util.COMMAND_EXTEND_SERIAL_PORT_GET_UPWARD
import com.ejlchina.tool.util.COMMAND_FULL_AND_DISTANCE_SET_DOWNWARD
import com.ejlchina.tool.util.COMMAND_FULL_AND_DISTANCE_SET_UPWARD
import com.ejlchina.tool.util.COMMAND_FULL_STATE_GET_DOWNWARD
import com.ejlchina.tool.util.COMMAND_FULL_STATE_GET_UPWARD
import com.ejlchina.tool.util.LOG_TAG
import com.ejlchina.tool.util.SUB_COMMAND_1
import com.ejlchina.tool.util.bytearray.intTo32HexStringLE
import com.ejlchina.tool.util.bytearray.readByteArrayLE
import com.ejlchina.tool.util.bytearray.readInt32LE
import com.ejlchina.tool.util.getBitValueFrom32Bits
import com.ejlchina.tool.util.showToast
import com.huyuhui.fastble.data.BleDevice
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.launch
import java.math.BigDecimal
import java.math.RoundingMode

class FullAndDistancePagerFragment(val bleDeviceBean: BleDeviceBean): BaseBindingFragment<FragmentFullAndDistancePagerBinding>(
    FragmentFullAndDistancePagerBinding::inflate) {

    private var fullStateFlow: Job? = null
    private var isSetNearDistance = 0
    private var isLaserOn: Boolean = false

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViews()
    }

    private fun initViews(){
        initListeners()

    }


    fun setViewState(){
        binding.layoutNoContent.visibility = if (isLaserOn) View.GONE else View.VISIBLE
        binding.layoutFullDistance.visibility = if (isLaserOn) View.VISIBLE else View.GONE
    }
    private fun getFullState(){
        if (isSetNearDistance == 1){
            showLoading()
        }

        fullStateFlow = viewLifecycleOwner.lifecycleScope.launch {
            IntRange(1, Int.MAX_VALUE).asFlow().collect{
                delay(800)
                getCommandData(bleDeviceBean,COMMAND_FULL_STATE_GET_DOWNWARD,"",false)

            }
        }

    }

    private fun initListeners(){
        binding.tvFarDistanceSend.setOnClickListener {
            isSetNearDistance = 1
            getFullState()
        }

        binding.btnConfirm.setOnClickListener {
            if (!checkIsDataValidate()){
                return@setOnClickListener
            }
            isSetNearDistance = 3
            setCommandData(
                bleDeviceBean,
                COMMAND_FULL_AND_DISTANCE_SET_DOWNWARD,
                SUB_COMMAND_1 +
                        intTo32HexStringLE((binding.tvNearDistance.text.toString().toFloat() * 1000).toInt()) +
                        intTo32HexStringLE((binding.etFarDistance.text.toString().toFloat() * 1000).toInt())
            )
            fullStateFlow?.cancel()
        }
    }

    private fun checkIsLaserOn(){
        getCommandData(bleDeviceBean, COMMAND_EXTEND_SERIAL_PORT_GET_DOWNWARD)
    }

    private fun checkIsDataValidate(): Boolean{
        val farDistance = binding.etFarDistance.text.toString().toFloat()
        val nearDistance = binding.tvNearDistance.text.toString().toFloat()
        if (nearDistance <= 0.2f){
            showToast("近距需要大于0.2M")
            return false
        }
        if (farDistance >= 4f){
            showToast("远距需要小于4M")
            return false
        }
        if (farDistance < nearDistance){
            showToast("远距需要大于近距")
            return false
        }
        return true
    }

    override fun whenReceiveCommand(bleDevice: BleDeviceBean,command: String, dataByteArray: ByteArray) {
        super.whenReceiveCommand(bleDevice,command, dataByteArray)
        if (bleDevice.bleDevice.mac != bleDeviceBean.bleDevice.mac) return
        dismissLoading()
        when(command){
            COMMAND_EXTEND_SERIAL_PORT_GET_UPWARD -> {
                val portByteArray = dataByteArray.readByteArrayLE(1,4)
                val laserState = getBitValueFrom32Bits(portByteArray,0) == OnOffEnum.ON.value
                Log.i(LOG_TAG,"*********************$laserState")
                binding.layoutNoContent.visibility = if (laserState) View.GONE else View.VISIBLE
                binding.layoutFullDistance.visibility = if (laserState) View.VISIBLE else View.GONE
            }

            COMMAND_FULL_AND_DISTANCE_SET_UPWARD -> {
                if (dataByteArray[dataByteArray.size - 1].toInt() == SuccessFailEnum.SUCCESS.value){
                    showToast("设置成功")
                } else {
                    showToast("设置失败")
                }
            }

            COMMAND_FULL_STATE_GET_UPWARD -> {
                binding.btnConfirm.visibility = View.VISIBLE
                val number = (dataByteArray.copyOfRange(3,dataByteArray.size).readInt32LE() / 1000F).toDouble()
                val num = BigDecimal(number)
                val roundedNumber = num.setScale(2, RoundingMode.HALF_UP).toFloat()
                val isFull = dataByteArray[1].toInt() == 1
                val percent = dataByteArray[2].toInt()
                val distance = dataByteArray.copyOfRange(3,dataByteArray.size).readInt32LE(0)
                Log.i(LOG_TAG,"isFill--${isFull}----percent---${percent}---distance---${distance}")
                when(isSetNearDistance){
                    1 -> {
                        binding.etFarDistance.setText(roundedNumber.toString())
                        isSetNearDistance = 2
                    }

                    2 -> {
                        binding.tvNearDistance.text = roundedNumber.toString()
                    }
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        checkIsLaserOn()
    }
}